<template>
  <div>
    <h1>购物车</h1>
    <table>
      <thead>
        <tr>
          <th>
            <input
              type="checkbox"
              v-model="isAllChecked"
              @change="handleAllCheck"
            />
            全选
          </th>
          <th>商品</th>
          <th>单价</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in shopData" :key="index">
          <td>
            <input
              type="checkbox"
              v-model="item.checked"
              @change="handleCheck"
            />
          </td>
          <td><img :src="item.imgUrl" width="50px" /> {{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="item.count > 1 ? item.count-- : (item.count = 1)">
              -</button
            ><input type="text" style="width: 30px" v-model="item.count" />
            <button @click="item.count < 10 && item.count++" class="right">
              +
            </button>
          </td>
          <td>{{ item.price * item.count }}</td>
          <td><button>删除</button></td>
        </tr>
      </tbody>
    </table>
    <div class="total">总数量: {{ calcTotalCount }} - 总价格:{{calcTotalPrice}}</div>
  </div>
</template>

<script>
export default {
  //数据先行
  data() {
    return {
      //购物车数据
      shopData: [
        { checked: false, name: '方便面', imgUrl: require('./assets/logo.png'), price: 1000, count: 1 },
        { checked: false, name: '泡  面', imgUrl: require('./assets/logo.png'), price: 2000, count: 1 },
        { checked: false, name: '干脆面', imgUrl: require('./assets/logo.png'), price: 3000, count: 1 },
        { checked: false, name: '火鸡面', imgUrl: require('./assets/logo.png'), price: 4000, count: 1 },
      ],
      isAllChecked: false

    }
  },
  //方法,事件
  methods: {
    //全选
    handleAllCheck() {
      this.shopData.forEach(v => {
        v.checked = this.isAllChecked
      })
    },
    //每一项选定
    handleCheck() {
      this.isAllChecked = this.shopData.every(v => {
        return v.checked
      })

    }
  },
  //计算属性
  computed: {
    //总数量
    calcTotalCount() {
      console.log(this.shopData);
      let temp = 0;
      this.shopData.filter(v =>  v.checked ).forEach(v => {
        temp += v.count
      })
      return temp
    },
    //总价格
    calcTotalPrice(){
      let temp=0;
      this.shopData.filter(v=> v.checked).forEach(v=> {
        temp+=v.price*v.count

      })
      return temp

    }
  }
}
</script>

<style lang="scss" scoped>
img {
  vertical-align: middle;
}
table {
  width: 800px;
  text-align: center;
  margin: 20px auto;
}
.total {
  width: 200px;
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  background-color: aqua;
  text-align: center;
  margin: 10px auto;
}
.right {
  margin-left: -5px;
}
</style>